# -*- coding: utf-8 -*-
from case_util.interface_test import config_parser
import json
from pymysql.pymysql import DB
import MySQLdb
import logging


class BasicInterface:
    def add_product(self, name, zt_product_id, description):
        isok = DB('db0').Table('product').Insert(
            {'name': name, 'zt_product_id': zt_product_id, 'description': description})
        if isok:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message']})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
            return json.dumps({'code': cm['code'], 'message': cm['message']})

    def get_products(self, name=None):
        if name:
            products = DB('db0').Select('name,description').From('product').Where('name=?', [name]).GetAll()
            if products:
                cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': products})
            else:
                cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': products})
        else:
            products = DB('db0').Select('name,description').From('product').GetAll()
            if products:
                cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': products})
            else:
                cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': products})

    # TODO 待定
    def get_project(self, product_id=None, name=None):
        if product_id and name:
            project_ids = DB('db0').Select('id,name,description,product_id').From('project').Where(
                'product_id=? and name=?',
                [product_id, name]).GetAll()
            if project_ids:
                projects = []
                for i in project_ids:
                    project = {}
                    project['id'] = i['id']
                    project['name'] = i['name']
                    project['description'] = i['description']
                    project['product_name'] = \
                        DB('db0').Select('name').From('product').Where('product_id=?', [i['product_id']]).GetAll()[0][
                            'name']
                    project['api_count'] = \
                        DB('db0').Select('count(id) counts').From('project_interface_ref').GetAll()[0]['counts']
                    projects.append(project)
                cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': projects})
        elif product_id or name:
            if product_id:
                project_ids = DB('db0').Select('id,name,description,product_id').From('project').Where(
                    'product_id=?', [product_id]).GetAll()
                if project_ids:
                    projects = []
                    for i in project_ids:
                        project = {}
                        project['id'] = i['id']
                        project['name'] = i['name']
                        project['description'] = i['description']
                        project['product_name'] = \
                            DB('db0').Select('name').From('product').Where('product_id=?', [i['product_id']]).GetAll()[
                                0][
                                'name']
                        project['api_count'] = \
                            DB('db0').Select('count(id) counts').From('project_interface_ref').GetAll()[0]['counts']
                        projects.append(project)
                    cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
                    return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': projects})
                else:
                    cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
                    return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})

            elif name:
                project_ids = DB('db0').Select('id,name,description,product_id').From('project').Where(
                    'name=?', [name]).GetAll()
                if project_ids:
                    projects = []
                    for i in project_ids:
                        project = {}
                        project['id'] = i['id']
                        project['name'] = i['name']
                        project['description'] = i['description']
                        project['product_name'] = \
                            DB('db0').Select('name').From('product').Where('product_id=?', [i['product_id']]).GetAll()[
                                0][
                                'name']
                        project['api_count'] = \
                            DB('db0').Select('count(id) counts').From('project_interface_ref').GetAll()[0]['counts']
                        projects.append(project)
                    cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
                    return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': projects})
                else:
                    cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
                    return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})

        else:
            project_ids = DB('db0').Select('id,name,description,product_id').From('project').GetAll()
            if project_ids:
                projects = []
                for i in project_ids:
                    project = {}
                    project['id'] = i['id']
                    project['name'] = i['name']
                    project['description'] = i['description']
                    project['product_name'] = \
                        DB('db0').Select('name').From('product').Where('product_id=?', [i['product_id']]).GetAll()[0][
                            'name']
                    project['api_count'] = \
                        DB('db0').Select('count(id) counts').From('project_interface_ref').GetAll()[0]['counts']
                    projects.append(project)
                cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': projects})
            else:
                cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})

    def relevance_api_for_project(self, project_id, api_id):
        isok = DB('db0').Table('project_interface_ref').Insert({'project_id': project_id, 'api_id': api_id})
        if isok:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message']})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
            return json.dumps({'code': cm['code'], 'message': cm['message']})

    def remove_api_for_project(self, project_id, api_id):
        isok = DB('db0').Table('project_interface_ref').Where('project_id=? and api_id=?',
                                                              [project_id, api_id]).Delete()
        if isok:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message']})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
            return json.dumps({'code': cm['code'], 'message': cm['message']})

    # TODO 以上待测
    def get_api_list_for_project(self, project_id):
        product_id = DB('db0').Select('product_id').From('project').Where('project_id=?', [project_id]).GetAll()
        if product_id:
            # TODO product_name
            apis = DB('db0').Select('name,uri,description').From('api').Where('product_id=?', [product_id]).GetAll()
            if apis:
                cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': apis})
            else:
                cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})

    def add_env_config(self, product_id, name, domain, db_config):
        isok = DB('db0').Table('environment_config').Insert(
            {'name': name, 'product_id': product_id, 'domain': domain, 'db_config': db_config})
        if isok:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message']})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
            return json.dumps({'code': cm['code'], 'message': cm['message']})

    def get_env_configs(self, product_id=None):
        if product_id:
            env_configs = DB('db0').Select('p.name product_name,e.name,e.domain,e.db_config').From(
                'environment_config e').Join('product p', 'e.product_id=p.id').Where('e.product_id=?', [
                product_id]).GetAll()
            if env_configs:
                cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': env_configs})
            else:
                cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})
        else:
            env_configs = DB('db0').Select('p.name product_name,e.name,e.domain,e.db_config').From(
                'environment_config e').Join('product p', 'e.product_id=p.id').GetAll()
            if env_configs:
                cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': env_configs})
            else:
                cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
                return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})

    def update_env_config_status_by_id(self, env_config_id, status):
        data = {'status': status}
        isok = DB('db0').Table('environment_config').Where('id=?', [env_config_id]).Update(data)
        if isok:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message']})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'SAVE_FAILED')
            return json.dumps({'code': cm['code'], 'message': cm['message']})

    def test_db_congfig_connect_by_id(self, env_config_id):
        db_config = DB('db0').Select('db_config').From('environment_config').Where('id=?', [env_config_id]).GetAll()
        db_data = {}
        if db_config:
            db_config_data = db_config[0]['db_config'].replace('’', "'").replace('，', ',').replace('：', ":").replace(
                ' ', '')
            for i in db_config_data.split(','):
                db_data[i.split('=')[0]] = i.split('=')[1].strip("'")
        if db_data:
            try:
                conn = MySQLdb.Connect(host=db_data['host'], port=int(db_data['port']), user=db_data['user'],
                                       passwd=db_data['passwd'], db=db_data['db'])
                if conn:
                    conn.close()
                    cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
                    return json.dumps({'code': cm['code'], 'message': cm['message']})
            except MySQLdb.Error, e:
                return json.dumps({'code': e[0], 'message': e[1]})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
            return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})

    def get_api_list(self, product_id=None, uri=None, name=None):
        # TODO product_name
        flag = False
        colnum = ''
        args = []
        if name:
            colnum = colnum + 'name=?'
            args.append(name)
            flag = True
        if uri and flag:
            colnum = colnum + 'and uri=?'
            args.append(uri)
            flag = True
        elif uri:
            colnum = colnum + 'uri=?'
            args.append(uri)
            flag = True
        if product_id and flag:
            colnum = colnum + 'and product_id =?'
            args.append(product_id)
            flag = True
        elif product_id:
            colnum = colnum + 'product_id=?'
            args.append(product_id)
            flag = True
        if not flag:
            sql = " DB('db0').Select('id,uri,name,description').From('api').GetAll()"
        else:
            sql = " DB('db0').Select('id,uri,name,description').From('api').Where(%s, %s).GetAll()" % (
                "'" + colnum + "'", str(args))
        apis = eval(sql)
        if apis:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': apis})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
            return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})

    def get_api_info_by_api_id(self, api_id):
        apis = DB('db0').Select('name,uri,description').From('api').Where('id=?', [api_id]).GetAll()
        api_args = DB('db0').Select('args_name,data_type,check_type,check_value,note').From('api_args').Where(
            'api_id=?', [api_id]).GetAll()
        api_response = DB('db0').Select('field,data_type,description').From('api_response').Where('api_id=?',
                                                                                                  [api_id]).GetAll()
        api_response_codes = DB('db0').Select('code,description').From('api_response_codes').Where('api_id=?',
                                                                                                   [api_id]).GetAll()
        if apis:
            cm = config_parser('config', 'code.conf', 'CODE', 'SUCCESS')
            return json.dumps({'code': cm['code'], 'message': cm['message'],
                               'data': {'api': apis, 'api_args': api_args, 'api_response': api_response,
                                        'api_response_codes': api_response_codes}})
        else:
            cm = config_parser('config', 'code.conf', 'CODE', 'DATA_NOT_FOUND_ERROR')
            return json.dumps({'code': cm['code'], 'message': cm['message'], 'data': {}})
